package com.dzl.timer;

import com.dzl.constant.CommonConstants;
import com.dzl.moive.pojo.WelfareMovieCity;
import com.dzl.moive.pojo.WelfareMovieOrder;
import com.dzl.moive.service.WelfareMovieCinemaService;
import com.dzl.moive.service.WelfareMovieCityService;
import com.dzl.moive.service.WelfareMovieOrderService;
import com.dzl.moive.utils.MovieConstant;
import com.dzl.moive.utils.MovieUtils;
import com.dzl.util.EmptyUtils;
import com.dzl.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.Date;
import java.util.List;

/**
 * 电影相关定时任务类
 * @author liuguanjun
 * @date 2021/11/02 17:24
 */
@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class MovieTimerTask {

    //private static final Logger logger = Logger.getLogger(MovieTimerTask.class.getName());

    @Autowired
    private WelfareMovieCinemaService welfareMoiveCinemaService;
    @Autowired
    private WelfareMovieOrderService welfareMovieOrderService;
    @Autowired
    private WelfareMovieCityService welfareMovieCityService;

    /**
     * 定时获取影院信息
     * @author liuguanjun
     * @date 2021-11-02 18:09:39
     **/
    @Async
    @Scheduled(cron = "0 0/5 2,3 * * ?") //在每天凌晨2点到2:55期间和凌晨3点到3:55期间的每5分钟触发
    @Transactional(rollbackFor = Exception.class)
    public void snycMovieCinema() {
        log.info("-----------------------定时获取影院信息并同步，任务开始-----------------------");
        //加锁  10秒
        boolean lock = RedisUtil.tryLock("SNYC_MOVIE_CINEMA:" , 1000*10);
        if(lock){
            Integer pageNo = 10;
            Object pageNoRedis = RedisUtil.get("snycMovieCinemaPageNo");
            if(EmptyUtils.isNotEmpty(pageNoRedis)){
                pageNo = (Integer) pageNoRedis;
                RedisUtil.set("snycMovieCinemaPageNo", pageNo+1,60*60*1);//缓存1小时
                pageNo = pageNo +1;
            }else{
                RedisUtil.set("snycMovieCinemaPageNo", 10,60*60*1);//缓存1小时
            }
            log.info("-----------------------定时获取影院信息并同步，当前页数"+pageNo+"-----------------------");
            welfareMoiveCinemaService.snycMovieCinema(pageNo);
        }
    }

    /**
     * 每日04:30更新城市主表的isupdate值为0,isupdate:是否已全部更新该城市的影院信息
     * @author liuguanjun
     * @date 2021-11-09 16:59:39
     **/
    @Async
    @Scheduled(cron = "0 30 4 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateMovieCity() {
        log.info("每天 04:30 更新城市主表的isupdate值为0,isupdate:是否已全部更新该城市的影院信息");
        Example example_ = new Example(WelfareMovieCity.class);
        example_.createCriteria()
                .andEqualTo("parentcode", "0")
                .andEqualTo("isupdate", CommonConstants.YES);
        WelfareMovieCity updateWelfareMovieCityParam = new WelfareMovieCity();
        updateWelfareMovieCityParam.setIsupdate(CommonConstants.NO);
        RedisUtil.delete("snycMovieCinemaPageNo");
        welfareMovieCityService.updateByExampleSelective(updateWelfareMovieCityParam,example_);
    }

    /**
     * 查询15分钟内未支付订单并取消
     * @author liuguanjun
     * @date 2021-11-05 17:47:39
     **/
    @Async
    @Scheduled(cron = "0 */1 * * * ?") //1分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void cancelUnpaidMovieOrder() {
        log.info("-----------------------查询15分钟内未支付订单并取消，任务开始-----------------------");
        //加锁  5秒
        boolean lock = RedisUtil.tryLock("CANCEL_UNPAID_MOVIE_ORDER:" , 1000*5);
        if(lock){
            List<WelfareMovieOrder> list =  welfareMovieOrderService.selectUnpaidMovieOrder();
            if(EmptyUtils.isNotEmpty(list)){
                for (WelfareMovieOrder order:list) {
                    //查询未支付的订单
                    String tradeno = MovieUtils.getUnpaidMovieOrder(order.getMobile());
                    if(EmptyUtils.isNotEmpty(tradeno) && tradeno.equals(order.getTradeno())){
                        //取消订单
                        welfareMovieOrderService.cancelMovieOrder(order.getTradeno(),"超时取消订单");
                        /*Boolean b = welfareMovieOrderService.cancelMovieOrder(order.getTradeno());
                        if(b){
                            order.setPlatformStatus(MovieConstant.MOVIE_ORDER_PLATFORM_STATUS.CANCEL);
                            order.setUpdateTime(new Date());
                            welfareMovieOrderService.updateByPrimaryKeySelective(order);
                        }*/
                    }else{
                        //取消订单
                        order.setPlatformStatus(MovieConstant.MOVIE_ORDER_PLATFORM_STATUS.CANCEL);
                        order.setUpdateTime(new Date());
                        order.setCancelTime(new Date());
                        order.setRemark("超时取消订单");
                        welfareMovieOrderService.updateByPrimaryKeySelective(order);
                    }
                }
            }
            log.info("-----------------------查询15分钟内未支付订单并取消，任务结束-----------------------");
        }
    }

    /**
     * 每隔2分钟查一次在平台支付成功但在嘟嘟平台状态未更新的订单
     * @author liuguanjun
     * @date 2021-11-05 17:47:39
     **/
    @Async
    @Scheduled(cron = "0 */2 * * * ?") //2分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void selectPaidMovieOrder() {
        log.info("-----------------------每隔2分钟查一次在平台支付成功但在嘟嘟平台状态未更新的订单，任务开始-----------------------");
        //加锁  5秒
        boolean lock = RedisUtil.tryLock("SELECT_PAID_MOVIE_ORDER:" , 1000*2);
        if(lock){
            Example example= Example.builder(WelfareMovieOrder.class).where(Sqls.custom()
                    .andNotEqualTo("orderstatus","S")
                    .andIsNull("refundReason")
                    .andEqualTo("platformStatus", MovieConstant.MOVIE_ORDER_PLATFORM_STATUS.PAID))
                    .build();
            List<WelfareMovieOrder> list =  welfareMovieOrderService.selectByExample(example);
            if(EmptyUtils.isNotEmpty(list)){
                for (WelfareMovieOrder order:list) {
                    WelfareMovieOrder welfareMovieOrder = MovieUtils.getMovieOrderDetail(order.getTradeno());
                    if(EmptyUtils.isNotEmpty(welfareMovieOrder) && !welfareMovieOrder.getOrderstatus().equals(order.getOrderstatus())){
                        //修改订单状态
                        order.setOrderstatus(welfareMovieOrder.getOrderstatus());
                        order.setRefundReason(welfareMovieOrder.getRefundReason());
                        order.setSmscontent(welfareMovieOrder.getSmscontent());
                        order.setUpdateTime(new Date());
                        order.setTicketcode(welfareMovieOrder.getTicketcode());
                        if(welfareMovieOrder.getOrderstatus().equals("S")){
                            //设置订单取票码
                            setWelfareMovieOrderTicketCode(welfareMovieOrder,order);
                        }else if(welfareMovieOrder.getOrderstatus().equals("R")){
                            order.setRefundReason(welfareMovieOrder.getRefundReason());
                            if(EmptyUtils.isEmpty(order.getRefundReason())){
                                order.setRefundReason("嘟嘟api退款成功");
                            }
                        }else{
                            boolean b = MovieUtils.updateMovieOrderPayNotify(order.getTradeno(),order.getOutTradeNo());
                            if(b){
                                welfareMovieOrder = MovieUtils.getMovieOrderDetail(order.getTradeno());
                                //修改订单状态
                                order.setOrderstatus(welfareMovieOrder.getOrderstatus());
                                order.setRefundReason(welfareMovieOrder.getRefundReason());
                                order.setSmscontent(welfareMovieOrder.getSmscontent());
                                order.setTicketcode(welfareMovieOrder.getTicketcode());
                                order.setUpdateTime(new Date());
                                if(welfareMovieOrder.getOrderstatus().equals("S")){
                                    //设置订单取票码
                                    //setWelfareMovieOrderTicketCode(welfareMovieOrder,order);
                                }else if(welfareMovieOrder.getOrderstatus().equals("R")){
                                    order.setRefundReason(welfareMovieOrder.getRefundReason());
                                    if(EmptyUtils.isEmpty(order.getRefundReason())){
                                        order.setRefundReason("嘟嘟api退款成功");
                                    }
                                }
                            }
                        }
                        welfareMovieOrderService.updateByPrimaryKeySelective(order);
                    }
                }
            }
            log.info("-----------------------每隔2分钟查一次在平台支付成功但在嘟嘟平台状态未更新的订单，任务结束-----------------------");
        }
    }

    //设置订单的取票码
    private void setWelfareMovieOrderTicketCode(WelfareMovieOrder welfareMovieOrder, WelfareMovieOrder order){
        /*if(EmptyUtils.isNotEmpty(welfareMovieOrder.getTicketcodeList())){
            String ticketcode = "";
            for (WelfareMovieOrderTicketcodeList ticket: welfareMovieOrder.getTicketcodeList()) {
                if(ticket.getName().equals("取票码")){
                    ticketcode = ticketcode + ticket.getValue()+"|";
                }else{
                    ticketcode = welfareMovieOrder.getTicketcodeList().toString()+"|";
                    break;
                }
            }
            ticketcode = ticketcode.substring(0,ticketcode.length()-1);
            order.setTicketcode(ticketcode);
        }*/
        /*if(EmptyUtils.isNotEmpty(welfareMovieOrder.getSmscontent())){
            String ticketcode = "";
            if(welfareMovieOrder.getSmscontent().contains("序列号")){
                ticketcode = welfareMovieOrder.getSmscontent().split("序列号")[1];
                if(EmptyUtils.isNotEmpty(ticketcode)){
                    ticketcode = ticketcode.split("至影院")[0];
                    ticketcode = ticketcode.replaceAll(",","");
                    ticketcode = ticketcode.replaceAll("T","");
                    ticketcode = ticketcode.replaceAll("验证码","|");
                }
            }else if(welfareMovieOrder.getSmscontent().contains("取票码")){
                ticketcode = welfareMovieOrder.getSmscontent().split("取票码")[1];
                if(EmptyUtils.isNotEmpty(ticketcode)){
                    ticketcode = ticketcode.split("至影院")[0];
                }
            }
            order.setTicketcode(ticketcode);
        }*/
    }





}
